extends CharacterBody2D

@onready var sprite := $Sprite2D

var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity")

const base_move_speed : int = 160
const overhead_jump_height : int = 4
const base_jump_height : int = 64

var move_speed : float
var jump_height : float
var jump_velocity : float

var coin_count

var is_absolutely_gold : bool = false

func _ready() -> void:
	set_coin_count(0)

func collect_coin() -> void:
	set_coin_count(coin_count + 1)
	if coin_count == 5:
		is_absolutely_gold = true
		velocity.x = 0
		EventBus.player_goldened.emit()

func set_coin_count(value: int) -> void:
	coin_count = value

	jump_height = base_jump_height - 16 * coin_count
	# h = (v^2 - v0^2)/2g
	jump_velocity = -sqrt((jump_height + overhead_jump_height) * 2 * gravity)

	move_speed = base_move_speed - 10 * coin_count

	sprite.frame_coords.y = value

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta

	if is_absolutely_gold:
		move_and_slide()
		return

	# Handle Jump.
	if Input.is_action_just_pressed("player_jump") and is_on_floor():
		velocity.y = jump_velocity

	# Get the input direction and handle the movement/deceleration.
	var direction := Input.get_axis("player_left", "player_right")
	if direction:
		velocity.x = direction * move_speed
	else:
		velocity.x = move_toward(velocity.x, 0, move_speed)

	if direction > 0:
		sprite.frame_coords.x = 0
	elif direction < 0:
		sprite.frame_coords.x = 1

	move_and_slide()
